package com.atguigu.flink.chapter10;

import com.atguigu.flink.bean.OrderEvent;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.cep.CEP;
import org.apache.flink.cep.PatternSelectFunction;
import org.apache.flink.cep.PatternStream;
import org.apache.flink.cep.PatternTimeoutFunction;
import org.apache.flink.cep.nfa.aftermatch.AfterMatchSkipStrategy;
import org.apache.flink.cep.pattern.Pattern;
import org.apache.flink.cep.pattern.conditions.SimpleCondition;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.co.KeyedCoProcessFunction;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.time.Duration;
import java.util.List;
import java.util.Map;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2022/1/14 8:56
 */
public class Flink06_High_Order {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        
        KeyedStream<OrderEvent, Long> stream = env
            .readTextFile("input/OrderLog.csv")
            .map(line -> {
                String[] data = line.split(",");
                return new OrderEvent(
                    Long.valueOf(data[0]),
                    data[1],
                    data[2],
                    Long.valueOf(data[3]) * 1000
                );
            })
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<OrderEvent>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((order, ts) -> order.getEventTime())
            )
            .keyBy(OrderEvent::getOrderId);
        // 订单实时监控: 找到异常订单 -  pay超时支付   有pay没有create
        // 正常的里面: 只有pay没有create会进入到正常的里面去
        Pattern<OrderEvent, OrderEvent> pattern = Pattern
            // 整体匹配, 跳过局部
            .<OrderEvent>begin("create", AfterMatchSkipStrategy.skipPastLastEvent())
            .where(new SimpleCondition<OrderEvent>() {
                @Override
                public boolean filter(OrderEvent value) throws Exception {
                    return "create".equals(value.getEventType());
                }
            }).optional()  // create可以是出现一次或0次
            .next("pay")
            .where(new SimpleCondition<OrderEvent>() {
                @Override
                public boolean filter(OrderEvent value) throws Exception {
                    return "pay".equals(value.getEventType());
                }
            })
            .within(Time.seconds(45));
        
        PatternStream<OrderEvent> ps = CEP.pattern(stream, pattern);
        
        SingleOutputStreamOperator<OrderEvent> normal = ps.select(
            new OutputTag<OrderEvent>("timeout") {},
            new PatternTimeoutFunction<OrderEvent, OrderEvent>() {
                @Override
                public OrderEvent timeout(Map<String, List<OrderEvent>> map,
                                          long timeoutTimestamp) throws Exception {
                    // 取出超时的create
                    return map.get("create").get(0);
                }
            },
            new PatternSelectFunction<OrderEvent, OrderEvent>() {
                @Override
                public OrderEvent select(Map<String, List<OrderEvent>> map) throws Exception {
                    // 1creat和一个pay , 正常, 不要
                    
                    if (!map.containsKey("create")) {// 只有一个pay  需要
                        return map.get("pay").get(0);  // 把这个单独的pay返回
                    } else {  // 即有create又有pay, 则正常, 不需要
                        return new OrderEvent();
                    }
                }
            }
        );
        
        // 存储的是create 是那些 : 没有pay或者pay超时的支付的那些 create
        DataStream<OrderEvent> timeoutCreateStream = normal.getSideOutput(new OutputTag<OrderEvent>("timeout") {});
        // 要么单独有pay要么pay来的晚
        SingleOutputStreamOperator<OrderEvent> singlePayStream = normal.filter(event -> event.getOrderId() != null);
        
        // payStream中的记录如果在timeoutStream能找到对应的数据,则是迟到的pay
        timeoutCreateStream
            .connect(singlePayStream)
            .keyBy(OrderEvent::getOrderId, OrderEvent::getOrderId)
            .process(new KeyedCoProcessFunction<Long, OrderEvent, OrderEvent, String>() {
                private ValueState<OrderEvent> createState;
                
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    createState = getRuntimeContext().getState(new ValueStateDescriptor<OrderEvent>("createState", OrderEvent.class));
                    
                }
                @Override
                public void processElement1(OrderEvent create,
                                            Context ctx,
                                            Collector<String> out) throws Exception {
                    createState.update(create);
                }
                @Override
                public void processElement2(OrderEvent pay, Context ctx, Collector<String> out) throws Exception {
                    if (createState.value() == null) {
                        out.collect("订单: " + pay.getOrderId() + " 只有pay, 没有create");
                    } else {
                        out.collect("订单: " + pay.getOrderId() + " 超时支付");
                    }
                }
            })
            .print();
        
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
